<template>
  <el-card class="el-card--has-heading success">
    <div slot="header">
      <span>账户管理</span>
      <el-button
        style="float: right; padding: 3px 0"
        type="text"
        @click="onClickCreate"
        v-auth:[$P.system.account.create]
      >创建账户</el-button>
    </div>
    <v-table
      :dataSource="dataSource"
      :columns="filterColumn(columns,[$P.system.account.update, $P.system.account.delete])"
      :total="total"
      :loading="loading"
      v-bind="bindProps"
      v-on="bindListeners"
    ></v-table>

    <Modal
      :title="modalType === 'create' ? $t('createText') : $t('updateText')"
      :loading="modalLoading"
      :visible.sync="modalVisible"
      :width="$V.size.sm"
      :onOk="handleModalSubmit"
      :onCancel="handleRoleClose"
      :okText="modalType === 'create' ? $t('createText') : $t('updateText')"
    >
      <AccountForm
        :record="record"
        :types="accountTypeList"
        :roles="modalType === 'create' ? roleSelectsForCreation : roleSelectsForUpdate"
        ref="roleForm"
      />
    </Modal>
  </el-card>
</template>

<script>
import AccountForm from './components/AccountForm'
import {
  getAccountList,
  createAccount,
  updateAccount,
  deleteAccount,
  getAccountTypeList,
  getRoleSelectsForCreation,
  getRoleSelectsForUpdate,
  getAccountById,
  enableAccount,
  disableAccount,
  resetAccountPassword
} from '@/api'

import { primaryKey } from './model'
import { Query } from '@/mixins'

export default {
  mixins: [Query('query')],

  components: { AccountForm },
  data () {
    return {
      dataSource: [],
      loading: false,
      total: 0,
      columns: [
        { prop: 'accountName', label: '账户名称' },
        { prop: 'accountNumber', label: '账户账号' },
        {
          prop: 'accountEnable',
          label: '启用状态',
          minWidth: this.$V.cellSize.logic,
          formatter: row => (
            <el-link
              disabled={!row.canEnable}
              type={!row.accountEnable || !row.canEnable ? 'danger' : 'success'}
              onClick={() => this.toggleStatus(!row.accountEnable, row)}
            >
              {row.accountEnable ? '是' : '否'}
            </el-link>
          )
        },
        { prop: 'accountCreateTime', label: '创建时间', width: this.$V.cellSize.date, formatter: row => this.$formatTime(row['accountCreateTime']) },
        { prop: 'accountCreateUserName', label: '创建人' },
        { prop: 'accountUpdateTime', label: '修改时间', width: this.$V.cellSize.date, formatter: row => this.$formatTime(row['accountUpdateTime']) },
        { prop: 'accountUpdateUserName', label: '修改人' },
        {
          label: '操作',
          minWidth: this.$V.cellSize.action,

          formatter: this.getActionDecorator([
            {
              icon: 'el-icon-edit',
              action: this.onClickUpdate,
              type: 'primary',
              auth: this.$P.system.account.update,
              render: row => row.canEdit
            },
            {
              icon: 'el-icon-delete',
              action: this.onClickDelete,
              type: 'danger',
              auth: this.$P.system.account.delete,
              render: row => row.canDelete
            },
            {
              icon: 'el-icon-refresh-left',
              auth: this.$P.system.account.resetPassword,
              action: this.onClickResetPassword,
              type: 'primary'
            }
          ])
        }
      ],

      // -------- Account Modal ----------
      accountTypeList: [],
      roleSelectsForCreation: [],
      roleSelectsForUpdate: [],
      record: {},
      // 当前账号类型用于查询角色
      curAccountType: '',
      modalType: '',
      modalVisible: false,
      modalLoading: false
      // -------- !Account Modal ----------
    }
  },
  methods: {
    // Requests
    // ------------------------------------------
    getAccountList (fn) {
      return this.Catch(getAccountList, {
        onOk (res) {
          this.dataSource = res.data.data
          this.total = res.data.total
        }
      })('loading', (fn || this.$noop)(this.query))
    },

    getAccountById (id, { onOk }) {
      return this.Catch(getAccountById, {
        onOk
      })('loading', id)
    },

    deleteAccount (id, { onOk }) {
      return this.Catch(deleteAccount, {
        onOk
      })(null, id)
    },

    createAccount (data) {
      return this.Catch(createAccount, {
        onOk () {
          this.$message.success(this.$t('createOk'))
          this.getAccountList()
          this.modalVisible = false
        }
      })('modalLoading', data)
    },

    updateAccount (id, data) {
      return this.Catch(updateAccount, {
        onOk () {
          this.$message.success(this.$t('updateOk'))
          this.getAccountList()
          this.modalVisible = false
        }
      })('modalLoading', id, data)
    },

    getAccountTypeList (loading) {
      if (this.accountTypeList.length) {
        return Promise.resolve()
      }

      return this.Catch(getAccountTypeList, {
        onOk ({ data }) {
          this.accountTypeList = data.map(it => ({
            label: it.name,
            value: this.$toNumber(it.code)
          }))
        }
      })(loading)
    },

    getRoleSelectsForCreation (loading) {
      if (this.roleSelectsForCreation.length) {
        return Promise.resolve()
      }

      return this.Catch(getRoleSelectsForCreation, {
        onOk ({ data }) {
          this.roleSelectsForCreation = data.map(it => ({
            label: it.roleName,
            value: it.roleId
          }))
        },
        onError () {}
      })(loading)
    },

    getRoleSelectsForUpdate (loading) {
      return this.Catch(getRoleSelectsForUpdate, {
        onOk ({ data }) {
          this.roleSelectsForUpdate = data.map(it => ({
            label: it.roleName,
            value: it.roleId
          }))
        }
      })(loading, this.curAccountType)
    },

    enableAccount (id) {
      return this.Catch(enableAccount, {
        onOk () {
          this.$message.success('启用成功')
          this.getAccountList()
        }
      })(null, id)
    },

    resetAccountPassword (id) {
      return this.Catch(resetAccountPassword, {
        onOk () {
          this.$message.success('重置成功')
          this.getAccountList()
        }
      })(null, id)
    },

    disableAccount (id) {
      return this.Catch(disableAccount, {
        onOk () {
          this.$message.success('禁用成功')
          this.getAccountList()
        }
      })(null, id)
    },

    // Table
    // ------------------------------------------

    toggleStatus (willEnable, row) {
      const message = willEnable
        ? '确认要启用所选的账号？'
        : '确认要禁用所选的账号？'
      this.MessageBox({
        type: 'warning',
        message,
        onOk: () =>
          willEnable
            ? this.enableAccount(row[primaryKey])
            : this.disableAccount(row[primaryKey])
      })
    },

    onClickResetPassword (row) {
      this.MessageBox({
        type: 'warning',
        message: '确认要重置所选账号密码吗？',
        onOk: () => this.resetAccountPassword(row[primaryKey])
      })
    },

    ensureAllList () {
      const tasks = Promise.all([
        this.modalType === 'create'
          ? this.getRoleSelectsForCreation(null)
          : this.getRoleSelectsForUpdate(null)
      ])
      return this.Catch(tasks, {
        onError () {}
      })('loading')
    },

    onClickDelete (row) {
      this.ConfirmDelete({
        onOk: () =>
          this.deleteAccount(row[primaryKey], {
            onOk () {
              this.$message.success(this.$t('deleteOk'))
              this.getAccountList()
            }
          })
      })
    },

    async onClickUpdate (row) {
      this.modalType = 'update'
      this.curAccountType = row.accountType

      await this.ensureAllList()

      this.getAccountById(row[primaryKey], {
        onOk ({ data }) {
          this.record = data
          this.modalVisible = true
        }
      })
    },

    async onClickCreate () {
      this.modalType = 'create'
      await this.ensureAllList()
      this.record = {}
      this.modalVisible = true
    },

    // Modal
    // ------------------------------------------

    // 关闭modal清理数据
    handleClose () {
      this.visible = false
    },

    handleModalSubmit () {
      this.$refs.roleForm.submit((valid, values) => {
        if (valid) {
          if (this.modalType === 'create') {
            this.createAccount(values)
          } else {
            this.updateAccount(values[primaryKey], values)
          }
        }
      })
    },

    handleRoleClose () {
      this.modalVisible = false
      this.record = {}
      this.modalType = ''
    }
  },
  computed: {},

  created () {
    this.getAccountList()
    this.inject(this.getAccountList)
  }
}
</script>
